using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using PackTracker.Business;

namespace PackTracker.UserControls
{
	public partial class ClienteEditar : UserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				clienteForm.DefaultMode = getCliente().IsNew ? FormViewMode.Edit : FormViewMode.ReadOnly;
				ApplyAuthorizationRules();
			}
		}

		#region Metodos privados

		private void ApplyAuthorizationRules()
		{
			//clienteButton.Visible = PackTracker.Business.Cliente.CanAddObject();
		}

		private void setCliente(Cliente cliente, bool salvar)
		{
			if (salvar)
			{
				cliente = cliente.Save();
				ViewState["Cliente"] = Cliente.GetCliente(cliente.Id);
			}
			else
			{
				ViewState["Cliente"] = cliente;
			}
		}

		protected Cliente getCliente()
		{
			int clienteId = 0;
			Cliente cliente = ViewState["Cliente"] as Cliente;

			if (cliente == null)
			{
				if (!String.IsNullOrEmpty(Request.QueryString["ClienteId"]))
					int.TryParse(Request.QueryString["ClienteId"].ToString(), out clienteId);

				cliente = (clienteId == 0) ? Cliente.NewCliente() : Cliente.GetCliente(clienteId);
				ViewState.Add("Cliente", cliente);
			}
			return cliente;
		}

		#endregion

		#region ClienteForm

		protected void clienteForm_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
		{
			Cliente cliente = getCliente();
			Csla.Data.DataMapper.Map(e.NewValues, cliente, "Id");
			setCliente(cliente, true);
			
			clienteForm.DefaultMode = FormViewMode.ReadOnly;
            clienteForm.DataBind();
		}
		
        protected void clienteForm_ItemCommand(object sender, FormViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Cancel":
                    clienteForm.DefaultMode = FormViewMode.ReadOnly;
                    clienteForm.DataBind();
                    break;
                case "Edit":
                    clienteForm.DefaultMode = FormViewMode.Edit;
                    ApplyAuthorizationRules();
                    break;
            }
        }
        
        protected void clienteForm_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {
            Cliente.DeleteCliente(getCliente().Id);
        }
		
		#endregion
		
		#region DataSources

		protected void clienteDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
		{
			e.BusinessObject = getCliente();
		}

		protected void idUsuarioListDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
		{
			e.BusinessObject = UsuarioCollection.GetUsuarioCollection();
		}

		protected void idEnderecoListDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
		{
			e.BusinessObject = EnderecoCollection.GetEnderecoCollection();
		}

		#endregion
		
    }
}
